<template>
	<d2-container>
		<!-- 页头部分 -->
		<template slot="header">
			<el-form ref="queryForm" :model="queryForm" class="header-area" label-width="100px" style="height:auto">
				<el-row>
					<el-col :span="4">
						<el-form-item label="仓库名称" prop="repositoryName">
							<el-input type="text" v-model="queryForm.repositoryName" placeholder="请输入仓库名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="仓库地址" prop="location">
							<el-input type="text" v-model="queryForm.location" placeholder="请输入仓库地址"></el-input>
						</el-form-item>
					</el-col>
          <el-col :span="4">
						<el-form-item label="启用状态" prop="status">
							<el-select v-model="queryForm.status" placeholder="请选择">
								<el-option label="全部" value=""></el-option>
								<el-option label="禁用" value="0"></el-option>
								<el-option label="启用" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="创建时间" prop="time">
								<el-date-picker
									v-model="time"
									type="datetimerange"
									:picker-options="pickerOptions"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="timestamp"
									align="right"
								></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<div class="search-submit">
							<el-button type="primary" size="medium" @click="submitForm('queryForm')">查询</el-button>
							<el-button size="medium" @click="resetForm('queryForm')">重置</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<!-- 主体部分 -->
		<template>
			<!-- 表格上方的按钮 -->
			<div class="table-header">
				<el-button type="primary" @click="showAddDialog">新增仓库</el-button>
			</div>

			<!-- 表格 -->
			<!-- 表格统一用 带边框、条纹间隔 的样式 -->
			<el-table :data="tableData" stripe border style="width: 100%">
				<el-table-column type="index" fixed label="序号" width="50"></el-table-column>
				<el-table-column label="仓库编号" prop="repositoryCode" width="200"></el-table-column>
				<el-table-column label="仓库名称" prop="repositoryName" width="160"></el-table-column>
				<el-table-column label="上级仓库" prop="parentName" width="160"></el-table-column>
        <el-table-column label="所属门店" prop="shopName" width="160"></el-table-column>
        <el-table-column label="库存类型" prop="stockType" width="100">
          <template slot-scope="scope">
                        <el-tag v-if="scope.row.stockType==1">线下</el-tag>
                        <el-tag v-if="scope.row.stockType==2">线上</el-tag>
          </template>
        </el-table-column>
				<el-table-column label="仓库地址" prop="location"></el-table-column>
				<el-table-column label="启用状态"  prop="status" width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status==0" style="color:#909399;background-color: white;">禁用</el-tag>
                        <el-tag v-if="scope.row.status==1">启用</el-tag>
                    </template>
        </el-table-column>
				<el-table-column label="创建时间"  prop="createTime"  :formatter="forDateCreate" width="150"></el-table-column>
				<el-table-column label="操作" fixed="right" width="220">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status==0" type="success" size="small" @click="restartCooperation(scope.$index, scope.row)">启用</el-button>
                        <el-button v-if="scope.row.status==1" type="info" size="small" @click="suspendCooperation(scope.$index, scope.row)">停用</el-button>
                        <el-button type="primary" size="small" @click="showEditDialog(scope.row)">编辑</el-button>
                        <el-button @click.native.prevent="deleteRow(scope.row)" type="danger" size="small">删除</el-button>
                    </template>
				</el-table-column>
			</el-table>
		</template>

		<!-- 页脚部分 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>

		<!-- 新增窗口 -->
		<template>
			<el-dialog title="仓库基本信息" width="60%" :visible.sync="showDialog" :before-close="handleCloseAdd">
				<div class="form-area">
					<el-form ref="addForm" :model="addForm" label-width="100px" style="height:auto" :rules="rules">
						<el-row>
							<el-col :span="12">
								<el-form-item label="仓库名称" prop="repositoryName">
									<el-input type="text" v-model="addForm.repositoryName" placeholder="请输入仓库名称"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="仓库编号" prop="repositoryCode">
									<el-input type="text" v-model="addForm.repositoryCode" placeholder="保存系统自动创建" readonly></el-input>
								</el-form-item>
							</el-col>
						</el-row>
            <el-row>
							<el-col :span="12">
								<el-form-item label="上级仓库" prop="parentId">
									<el-select v-model="addForm.parentId" style="width: 100%;">
										<el-option v-for="item in parentTable" :key="item.id" :label="item.repositoryName" :value="item.id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
                            <el-col :span="12">
								<el-form-item label="启用状态" prop="status">
									<el-select v-model="addForm.status" placeholder="请选择" style="width: 100%;">
										<el-option label="启用" value="1"></el-option>
										<el-option label="禁用" value="0"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
            <el-row>
							<el-col :span="12">
								<el-form-item label="所属门店" prop="shopId">
									<el-select v-model="addForm.shopId" placeholder="请选择所属门店" style="width: 100%;">
                    <el-option v-for=" item in shops" :key="item.id" :value="item.id" :label="item.shopName"></el-option>
                  </el-select>
								</el-form-item>
							</el-col>
              <el-col :span="12">
								<el-form-item label="库存类型" prop="stockType">
									<el-select v-model="addForm.stockType" placeholder="请选择库存类型" style="width: 100%;">
										<el-option label="线下" value="1"></el-option>
										<el-option label="线上" value="2"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
                        <el-row>
							<el-col :span="24">
								<el-form-item label="仓库地址" prop="location">
									<el-input type="text" rows="5" v-model="addForm.location"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
                        <el-row>
							<el-col :span="24">
								<el-form-item label="备注" prop="remark">
									<el-input type="textarea" rows="5" v-model="addForm.remark"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>

				<div class="dialog-footer" slot="footer">
					<el-button type="primary" @click="addSave('addForm')">保存</el-button>
					<el-button @click="clearAddForm">取消</el-button>
				</div>
			</el-dialog>
		</template>

		<!-- 编辑窗口 -->
		<template>
			<el-dialog title="仓库基本信息" width="60%" :visible.sync="showDialogEdit" :before-close="handleCloseEdit">
				<div class="form-area">
					<el-form ref="editForm" :model="editForm" label-width="100px" style="height:auto" :rules="rules">
						<el-row>
							<el-col :span="12">
								<el-form-item label="仓库名称" prop="repositoryName">
									<el-input type="text" v-model="editForm.repositoryName" placeholder="请输入仓库名称"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="仓库编号" prop="repositoryCode">
									<el-input type="text" v-model="editForm.repositoryCode" readonly></el-input>
								</el-form-item>
							</el-col>
						</el-row>
                        <el-row>
							<el-col :span="12">
								<el-form-item label="上级仓库" prop="parentId">
									<el-select v-model="editForm.parentId" style="width: 100%;">
										<el-option v-for="item in parentTable" :key="item.id" :label="item.repositoryName" :value="item.id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
                            <el-col :span="12">
								<el-form-item label="启用状态" prop="status">
									<el-select v-model="editForm.status" placeholder="请选择" style="width: 100%;">
										<el-option label="启用" value="1"></el-option>
										<el-option label="禁用" value="0"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
            <el-row>
							<el-col :span="12">
								<el-form-item label="所属门店" prop="shopId">
									<el-select v-model="editForm.shopId" placeholder="请选择所属门店" style="width: 100%;">
                    <el-option v-for=" item in shops" :key="item.id" :value="item.id" :label="item.shopName"></el-option>
                  </el-select>
								</el-form-item>
							</el-col>
              <el-col :span="12">
								<el-form-item label="库存类型" prop="stockType">
									<el-select v-model="editForm.stockType" placeholder="请选择库存类型" style="width: 100%;">
										<el-option label="线下" value="1"></el-option>
										<el-option label="线上" value="2"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
                        <el-row>
							<el-col :span="24">
								<el-form-item label="仓库地址" prop="location">
									<el-input type="text" rows="5" v-model="editForm.location"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
                        <el-row>
							<el-col :span="24">
								<el-form-item label="备注" prop="remark">
									<el-input type="textarea" rows="5" v-model="editForm.remark"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>

				<div class="dialog-footer" slot="footer">
					<el-button type="primary" @click="editSave('editForm')">保存</el-button>
					<el-button @click="clearEditForm">取消</el-button>
				</div>
			</el-dialog>
		</template>
	</d2-container>
</template>

<script>
import { 
getRepositoryListByPage,
findRepositoryById, 
enableRepositoryInfo, 
unenableRepositoryInfo,
deleteRepositoryInfo, 
findRepositoryInfoNotCurrent, 
addSaveRepository,
editSaveRepository
} from '@api/repository/repositoryInfo'
import { getShops } from '@api/shop/shop'
import dayjs from 'dayjs'
export default {
  data () {
    return {
      queryForm: {
        repositoryName: '',
        location: '',
        startTime: '',
        endTime: '',
        status: ''
      },
      shops:[],
      addForm: {
        repositoryName: '',
        repositoryCode: '',
        parentId: 0,
        status: '1',
        location: '',
        remark: '',
        shopId: '',
        stockType: ''
      },
      editForm: {
        repositoryName: '',
        repositoryCode: '',
        parentId: 0,
        status: '',
        location: '',
        remark: '',
        shopId: '',
        stockType: ''
      },
	  parentTable: [],
      time: [],
	  tableData: [],
	  currentPage: 1,
	  pageSize: 10,
	  total: 0,

	  showDialog: false,
	  showDialogEdit: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      rules: {
        repositoryName: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '仓库地址不能为空', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '上级仓库不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '启用状态不能为空', trigger: 'blur' }
        ],
        shopId: [
          { required: true, message: '请选择所属门店', trigger: 'blur' }
        ],
        stockType: [
          { required: true, message: '请选择库存类型', trigger: 'blur' }
        ],
    	}
    }
  },
  methods: {
    fetchData () {
      this.loading = true
      this.queryForm.startTime = this.time[0]
      this.queryForm.endTime = this.time[1]
      this.queryForm.pageNum = this.currentPage
      this.queryForm.pageSize = this.pageSize
      getRepositoryListByPage(this.queryForm)
        .then(res => {
          this.tableData = res.data.content
          this.total = res.data.total
          this.loading = false
        })
        .catch(err => {
          console.error('异常信息: ', err)
          this.loading = false
        })
    },
	  submitForm (formName) {
      this.fetchData()
	  },
	  resetForm (formName) {
      this.$refs[formName].resetFields()
		  this.queryForm.startTime = ''
		  this.queryForm.endTime = ''
		  this.time = []
      this.fetchData()
	  },
	  handleSizeChange (val) {
	    this.pageSize = val
	  },
	  handleCurrentChange (val) {
	    this.currentPage = val
	  },
    forDateCreate (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.createTime).format('YYYY-MM-DD')
    },
    restartCooperation (index, row) {
      this.$confirm('是否确定启用【' + row.repositoryName + '】仓库？').then(_ => {
        this.loading = true
        enableRepositoryInfo({
          repositoryId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    suspendCooperation (index, row) {
      this.$confirm('是否确定停用【' + row.repositoryName + '】仓库？').then(_ => {
        this.loading = true
        unenableRepositoryInfo({
          repositoryId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    deleteRow (row) {
      this.$confirm('是否确定删除【' + row.repositoryName + '】仓库？').then(_ => {
        this.loading = true
        deleteRepositoryInfo({
          repositoryId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    fetchRepositoryInfoNotCurrent (id) {
      findRepositoryInfoNotCurrent({
        repositoryId: id
      })
        .then(res => {
          if (res.code == '000000') {
            this.parentTable = res.data
          } else {
            this.$message({ message: '上级仓库列表获取失败，请刷新页面重试', type: 'error' })
          }
        })
        .catch(err => {
          console.log('err', err)
          this.$message({ message: '上级仓库列表获取失败，请刷新页面重试', type: 'error' })
        })
    },
    fetchShop () {
      getShops({})
        .then(res => {
          if (res.code == '000000') {
            this.shops = res.data
          } else {
            console.log('err', err)
            this.loading = false
          }
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    fetchRepository (id) {
      findRepositoryById({
        repositoryId: id
      })
        .then(res => {
          if (res.code == '000000') {
            this.editForm = res.data
			  this.editForm.status += ''
        this.editForm.stockType += ''
          } else {
            this.$message({ message: res.message, type: 'error' })
          }
        })
        .catch(err => {
          console.log('err', err)
          this.$message({ message: res.message, type: 'error' })
        })
    },
    showAddDialog () {
      this.fetchRepositoryInfoNotCurrent()
      this.fetchShop()
      this.showDialog = true
    },
    addSave (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addSaveRepository(this.addForm)
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
			  this.$refs[formName].resetFields()
              this.showDialog = false
			  this.fetchData()
            })
            .catch((err) => {
              console.log('err', err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearAddForm () {
      this.addForm = {
        repositoryName: '',
        repositoryCode: '',
        parentId: 0,
        status: '1',
        location: '',
        remark: '',
        shopId: '',
        stockType: ''
      }
	  this.showDialog = false
    },
    handleCloseAdd (done) {
      this.clearAddForm()
      done()
    },
    showEditDialog (row) {
      this.fetchRepositoryInfoNotCurrent(row.id)
      this.fetchRepository(row.id)
      this.showDialogEdit = true
    },
    editSave (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          editSaveRepository(this.editForm)
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
			  this.$refs[formName].resetFields()
              this.showDialogEdit = false
			  this.fetchData()
            })
            .catch((err) => {
              console.log('err', err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearEditForm () {
      this.editForm = {
        repositoryName: '',
        repositoryCode: '',
        parentId: 0,
        status: '1',
        location: '',
        remark: '',
        shopId: '',
        stockType: ''
      }
	  this.showDialogEdit = false
    },
    handleCloseEdit (done) {
      this.clearEditForm()
      done()
    }
  },
  mounted () {
    this.fetchData()
  }
}
</script>

<style lang="scss" scoped>
	// 样式请务必加scoped

</style>
